﻿using System;
using System.Security.Cryptography;

using System.Text;

namespace Yhb.Utility
{
    public class RSAUtility
    {
        public static string ALGORITHM = "RSA";
        public static string CHAR_SET = "UTF-8";

        public static string GenerateKey(bool isPrivateKey)
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            return RSA.ToXmlString(isPrivateKey);
        }

        public static string Sign(string content, string privateKey)
        {
            try
            {

                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(privateKey);
                //签名返回
                var signData = rsa.SignData(Encoding.GetEncoding(CHAR_SET).GetBytes(content),"SHA256");
                return Convert.ToBase64String(signData);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
            return null;
        }

        public static bool Verify(string content, string sign,string public_key)
        {
            try
            {
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(public_key);
                bool bVerify = rsa.VerifyData(Encoding.GetEncoding(CHAR_SET).GetBytes(content),"SHA256",Convert.FromBase64String(sign));
                return bVerify;
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
            return false;
        }
    }
}
